//
//  JFAlertController.m
//  alertViewClass
//
//  Created by ranjingfu on 15/12/21.
//  Copyright © 2015年 ranjingfu. All rights reserved.
//

#import "JFAlertController.h"
#import <UIKit/UIKit.h>
typedef void(^userClickAction)(JFAlertAction *action);
static NSMutableArray   *arrayAlertController = nil;
@interface JFAlertAction ()
{
    NSString            *_title;
    JFAlertActionStyle   _style;
    BOOL                 _enabled;
}
@property(nonatomic,copy)userClickAction userAction;
@end

@implementation JFAlertAction
@synthesize title = _title;
@synthesize style = _style;
@synthesize enabled = _enabled;
@synthesize userAction;



+ (instancetype)actionWithTitle:(NSString *)newTitle style:(JFAlertActionStyle)style handler:(void (^)(JFAlertAction* action))handler
{
    JFAlertAction *alertAction = [[JFAlertAction alloc] initWithTitle:newTitle style:style handler:handler];
    return alertAction;
}

- (instancetype)initWithTitle:(NSString *)newTitle style:(JFAlertActionStyle)style handler:(void (^)(JFAlertAction* action))handler
{
    
    self = [super init];
    if (self)
    {
        _title = newTitle;
        _style = style;
        self.userAction = handler;
        self.enabled = YES;
    }
    
    return self;
}


@end
@interface JFAlertController ()<UIActionSheetDelegate>
{
    NSString    *_title;
    NSString    *_message;
    JFAlertControllerStyle _preferredStyle;
    JFAlertAction  *_preferredAction;
    
    NSMutableArray     *_textFields;
    NSMutableArray     *_actions;
}

//@property(nonatomic, strong)UIAlertView  *alertView;
@property(nonatomic, strong)UIActionSheet *actionSheet;
@property(nonatomic, strong)UIAlertController *alertController;
@property(nonatomic, weak)UIViewController  *presentViewController;
@end

@implementation JFAlertController
@synthesize title = _title;
@synthesize message = _message;
@synthesize preferredStyle = _preferredStyle;
@synthesize preferredAction = _preferredAction;

+ (instancetype)alertControllerWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(JFAlertControllerStyle)preferredStyle
{
    JFAlertController *controller = [[JFAlertController alloc] initWithTitle:title message:message preferredStyle:preferredStyle];
    return controller;
}

+ (instancetype)alertControllerWithTitle:(NSString *)title message:(NSString *)message cancelAction:(JFAlertAction*)cancelAction ensureAction:(JFAlertAction*)ensureAction
{
    JFAlertController *controller = [[JFAlertController alloc] initWithTitle:title message:message preferredStyle:JFAlertControllerStyleAlert];
    [controller addAction:cancelAction];
    [controller addAction:ensureAction];
    return controller;
}

- (instancetype)initWithTitle:(NSString *)title message:(NSString *)message preferredStyle:(JFAlertControllerStyle)preferredStyle
{
    self = [super init];
    if (self)
    {
        _title = title;
        _message = message;
        _preferredStyle = preferredStyle;
        if (NSClassFromString(@"UIAlertController"))
        {
            UIAlertControllerStyle style = UIAlertControllerStyleAlert;
            if (preferredStyle == JFAlertControllerStyleActionSheet)
            {
                style = UIAlertControllerStyleActionSheet;
            }
            
            self.alertController = [UIAlertController alertControllerWithTitle:title
                                                                       message:message
                                                                preferredStyle:style];
        }
    }
    return self;
}
-(UIAlertAction*)actionWithQWAction:(JFAlertAction*)qwAction
{
    UIAlertActionStyle style = UIAlertActionStyleDefault;
    if (qwAction.style == JFAlertActionStyleCancel)
    {
        style = UIAlertActionStyleCancel;
    }else if (qwAction.style == JFAlertActionStyleDefault)
    {
        style = UIAlertActionStyleDefault;
    }else if (qwAction.style ==  JFAlertActionStyleDestructive)
    {
        style = UIAlertActionStyleDestructive;
    }
    
    __weak typeof(JFAlertController) *weakSelf = self;
    UIAlertAction *alertAction = [UIAlertAction actionWithTitle:qwAction.title
                                                          style:style
                                                        handler:^(UIAlertAction *action) {
                                                            if (qwAction.userAction)
                                                            {
                                                                qwAction.userAction(qwAction);
                                                            }
                                                            [arrayAlertController removeObject:weakSelf];
                                                        }];
    alertAction.enabled = qwAction.enabled;
    return alertAction;
}

- (void)addAction:(JFAlertAction *)action
{
    if (!_actions)
    {
        _actions = [[NSMutableArray alloc] init];
    }
    
    NSAssert([action isKindOfClass:[JFAlertAction class]], nil);
    if (![action isKindOfClass:[JFAlertAction class]])
    {
        NSLog(@"add Action fail,please check your class pass to JFAlertController:%@",action);
        return;
    }
    if (action)
    {
        [_actions addObject:action];
        if (self.alertController)
        {
            [self.alertController addAction:[self actionWithQWAction:action]];
        }
    }
}

- (void)addActions:(NSArray*)arrayActions
{
    for (JFAlertAction *action in arrayActions)
    {
        [self addAction:action];
    }
}

-(NSArray*)actions
{
    return [NSArray arrayWithArray:_actions];
}
-(NSArray*)textFields
{
    return [NSArray arrayWithArray:self.alertController.textFields];
}

- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler
{
    [self.alertController addTextFieldWithConfigurationHandler:configurationHandler];
}


#pragma mark
#pragma mark present view
- (void)showInViewController:(UIViewController*)viewController
{
    [self showInViewController:viewController animated:YES compeleted:NULL];
}

- (void)showInViewController:(UIViewController*)viewController animated:(BOOL)animate
{
    [self showInViewController:viewController animated:animate compeleted:NULL];
}

- (void)showInViewController:(UIViewController*)viewController animated:(BOOL)animate compeleted:(void (^)())completed
{
    if (arrayAlertController == nil)
    {
        arrayAlertController = [[NSMutableArray alloc] init];
    }
    [arrayAlertController addObject:self];
    
    
    if (self.alertController == nil || viewController == nil)
    {
        NSMutableArray *arrayNewSort = [NSMutableArray arrayWithCapacity:_actions.count];
        JFAlertAction *cancelAction = nil;
        JFAlertAction *destructiveAction = nil;
        for (JFAlertAction  *action in _actions)
        {
            NSAssert(action.title != nil, @"presentInViewController fail bacause action title is nil:action");
            if (action.style == JFAlertActionStyleCancel)
            {
                cancelAction = action;
            }else if(action.style == JFAlertActionStyleDestructive)
            {
                destructiveAction = action;
            }else
            {
                [arrayNewSort addObject:action];
            }
       
        }
        if (destructiveAction)
        {
            [arrayNewSort addObject:destructiveAction];
        }
        if (cancelAction){
            [arrayNewSort addObject:cancelAction];
        }

        NSString  *content = nil;
        if ([_title length]){
            content = _title;
        }else{
            content = _message;
        }
            
        NSInteger destructiveIndex = -1;
        if (destructiveAction){
            destructiveIndex = [arrayNewSort indexOfObject:destructiveAction];
        }
            
        NSInteger cancelIndex = -1;
        if (cancelAction){
            cancelIndex = [arrayNewSort indexOfObject:cancelAction];
        }
            
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:content
                                                        delegate:self
                                                cancelButtonTitle:nil
                                            destructiveButtonTitle:nil
                                                otherButtonTitles:nil, nil];
            
        for (JFAlertAction  *action in arrayNewSort){
            [self.actionSheet addButtonWithTitle:action.title];
        }
            
        _actions = arrayNewSort;
        self.actionSheet.destructiveButtonIndex = destructiveIndex;
        self.actionSheet.cancelButtonIndex = cancelIndex;
        [self.actionSheet showInView:viewController.view];
        if (completed){
            completed();
        }
        return;
    }
  
    NSAssert(viewController != nil, @"presentInViewController fail because viewController is nil");
    if (self.alertController.popoverPresentationController) {
        UIPopoverPresentationController *pop =  self.alertController.popoverPresentationController;
        pop.sourceView = viewController.view;
        pop.sourceRect = CGRectMake(viewController.view.bounds.size.width / 2.0, viewController.view.bounds.size.height, 1.0, 1.0);
    }
    [viewController presentViewController:self.alertController
                                     animated:animate
                                   completion:completed];
    
    
}
/*
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex < _actions.count)
    {
        JFAlertAction  *action = [_actions objectAtIndex:buttonIndex];
        if (action.userAction)
        {
            action.userAction(action);
        }
    }
    [arrayAlertController removeObject:self];
}
// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
- (void)alertViewCancel:(UIAlertView *)alertView
{
    if (_actions.count > 0)
    {
        for (JFAlertAction *action in _actions)
        {
            if (action.style == JFAlertActionStyleCancel)
            {
                if (action.userAction)
                {
                    action.userAction(action);
                }
                break;
            }
        }
    }
 
}

- (void)willPresentAlertView:(UIAlertView *)alertView
{
    
}
- (void)didPresentAlertView:(UIAlertView *)alertView
{
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    [arrayAlertController removeObject:self];
}*/

#pragma mark
#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex < _actions.count)
    {
        JFAlertAction  *action = [_actions objectAtIndex:buttonIndex];
        if (action.userAction)
        {
            action.userAction(action);
        }
    }
}

// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
- (void)actionSheetCancel:(UIActionSheet *)actionSheet
{
    if (_actions.count > 0)
    {
        for (JFAlertAction *action in _actions)
        {
            if (action.style == JFAlertActionStyleCancel)
            {
                if (action.userAction)
                {
                    action.userAction(action);
                }
                break;
            }
        }
    }
}
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet
{
}
- (void)didPresentActionSheet:(UIActionSheet *)actionSheet
{
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex
{
}
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
       [arrayAlertController removeObject:self];
}
-(void)dealloc
{
    NSLog(@"JFAlertController dealloc");
}
@end
